package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.utils.DateUtil;

public class BroadStandardActivity extends AppCompatActivity implements View.OnClickListener {

    private final static String TAG = "BroadStandardActivity";
    //定义广播的动作名称
    private final static String STANDARD_ACTION = "com.example.myapplication";
    private TextView tv_standard;
    private String msg = "这里查看标准广播的收听信息";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broad_standard);
        tv_standard = findViewById(R.id.tv_standard);
        tv_standard.setText(msg);
        findViewById(R.id.bnt_send_standard).setOnClickListener(this);
    }

    /**
     * 点击事件发送广播
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bnt_send_standard){
            //1. 创建指定动作的意图
            Intent intent = new Intent(STANDARD_ACTION);
            //2. 发送标准广播
            sendBroadcast(intent);

        }
    }

    /**
     * 定义一个标准广播的接收器
     */
    private class StandardReceiver extends BroadcastReceiver{
        // 一旦接收到标准广播，马上触发接收器的onReceive方法
        @Override
        public void onReceive(Context context, Intent intent) {
            // 广播意图非空，且接头暗号正确
            if (intent != null && intent.getAction().equals(STANDARD_ACTION)){
                msg = String.format("%s\n%s收到一个标准广播",msg, DateUtil.getNowTime());
                tv_standard.setText(msg);
            }
        }
    }

    /**
     * 过滤器动作名称一致的广播,并注册接收器：动作名称类型WiFi名称
     */
   private StandardReceiver standardReceiver;
    @Override
    protected void onStart() {
        super.onStart();
        // 1. 声明一个标准广播的接收器实例
        standardReceiver = new StandardReceiver();
        // 2. 创建一个意图过滤器，只处理STANDARD_ACTION的广播
        IntentFilter intentFilter = new IntentFilter(STANDARD_ACTION);
        // 3. 注册接收器，注册之后才能正常接收广播
        registerReceiver(standardReceiver,intentFilter);
    }

    /**
     * 注销接收器
     */
    @Override
    protected void onStop() {
        super.onStop();
        // 注销接收器，注销之后就不再接收广播
        unregisterReceiver(standardReceiver);
    }
}
